package com.walk.zworld.ui.location

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.CountDownTimer
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.amap.api.maps2d.model.LatLng
import com.base.lib.base.utils.ToastUtil
import com.base.lib.base.utils.ToastUtil.showToast
import com.base.lib.base.view.BaseFragment
import com.base.lib.common.utils.SPUtils
import com.base.lib.httpUtils.Banner
import com.base.lib.net.utils.ThreadUtils
import com.walk.zworld.R
import com.walk.zworld.api.MainAPI
import com.walk.zworld.api.bean.AddressInfoBean
import com.walk.zworld.api.bean.BannerBean
import com.walk.zworld.api.bean.ConfigBean
import com.walk.zworld.api.bean.FeatureBean
import com.walk.zworld.api.bean.UserBean
import com.walk.zworld.api.http.BaseHttpCallBack
import com.walk.zworld.api.http.CommonAPI
import com.walk.zworld.api.http.CommonAppConfig
import com.walk.zworld.api.http.HttpCallback
import com.walk.zworld.api.http.ParseArrayHttpCallBack
import com.walk.zworld.api.http.ParseHttpCallback
import com.walk.zworld.api.utils.ListUtil
import com.walk.zworld.api.utils.MapBuilder
import com.walk.zworld.mvvm.vm.HomeViewModel
import com.walk.zworld.ui.adapter.ImageAdapter
import com.walk.zworld.utils.AllowMockLocationTools
import com.walk.zworld.utils.observer.DefaultObserver
import com.walk.zworld.utils.observer.DialogObserver
import com.walk.zworld.view.BannerView
import com.walk.zworld.view.banner.indicator.CircleIndicator
import com.walk.zworld.view.floatview.FloatClient
import com.walk.zworld.view.floatview.FloatHelper
import com.walk.zworld.view.floatview.utils.SettingsCompat
import com.walk.zworld.view.location.amap.AMapMapUtils
import com.walk.zworld.view.location.amap.LocationAmapSelectorActivity
import com.walk.zworld.webView.WebViewActivity

class LocationDetailFragment : BaseFragment(), View.OnClickListener {

    private var defLatLng: LatLng? = null
    private lateinit var do_start_btn: TextView
    private lateinit var do_start_text: TextView
    private lateinit var do_start_layout: LinearLayout
    private lateinit var tvAddress: TextView
    private lateinit var btn_start_text: View
    private lateinit var rikaselect: View
    private lateinit var progressViewHelper: LoactionDetailProgressViewHelper

    private lateinit var imgAdapter: ImageAdapter
    private var bannerView: BannerView<Banner, ImageAdapter>? = null

    companion object {
        fun newsInstance() = LocationDetailFragment()
    }

    override fun onBindLayout(): Int = R.layout.location_activity_detail

    override fun initView(mView: View) {
        tvAddress = findViewById<TextView>(R.id.tv_address)
        do_start_layout = findViewById<LinearLayout>(R.id.do_start_layout)
        do_start_layout.visibility = View.GONE
        do_start_text = findViewById<TextView>(R.id.do_start_text)
        do_start_btn = findViewById<TextView>(R.id.do_start_btn)

        progressViewHelper = LoactionDetailProgressViewHelper()
        locationTools = AllowMockLocationTools.with(activity)
        progressViewHelper.initView(activity, findViewById(R.id.location_progress))
        btn_start_text = findViewById<View>(R.id.btn_start_text)
        rikaselect = findViewById<View>(R.id.rikaselect)
        rikaselect.setOnClickListener {
            MainAPI.sendGift("999", "999", 1, "1", object : HttpCallback() {
                override fun onSuccess(code: Int, msg: String, info: Array<String>) {
                    if (code == 200) {
                        rikaselect.visibility = View.GONE
                        btn_start_text.visibility = View.VISIBLE
                        showToast("兑换成功，开始使用")
                    } else {
                        showToast(msg)
                    }
                }
            })
        }
        btn_start_text.setOnClickListener {
            initCountDown2(requireActivity(), null)
        }
        findViewById<TextView>(R.id.btn_start_location).setOnClickListener {
            val intent = Intent()
            intent.setClass(requireActivity(), LocationAmapSelectorActivity::class.java)
            startActivity(intent)
        }

        bannerView = findViewById(R.id.banner_view)
        bannerView?.run {
            addBannerLifecycleObserver(this@LocationDetailFragment)
            indicator = CircleIndicator(activity)
        }
        MainAPI.getFeatured(1).subscribe(object : DefaultObserver<FeatureBean?>() {
                override fun onNext(featureBean: FeatureBean) {
                    val list: List<BannerBean> = featureBean.getBanner()
                    val arrayList = ArrayList<Banner>()
                    for (bannerBean in list.reversed()) {
                        arrayList.add(Banner(bannerBean.name,bannerBean.id,"http://web.nowk.top"+bannerBean.pic,
                        1,0,bannerBean.name,0,bannerBean.url))
                    }
                    imgAdapter = ImageAdapter(requireActivity(), arrayList)
                    bannerView?.run {
                        setAdapter(imgAdapter, true)
                        setOnBannerListener { data, position ->
                            data as Banner
                            if (data.url.contains("http")) {
                                WebViewActivity.start(activity, data.id, data.title, data.url)
                            }
                        }
                    }
                }
            })
    }

    @SuppressLint("MissingPermission")
    override fun initData() {
        do_start_layout.visibility = View.GONE
        progressViewHelper.setStatus(-1)
//        btn_start_text.visibility = View.GONE
        val canDrawOverlays = SettingsCompat.canDrawOverlays(activity)
        val hasLocationPermission = locationTools?.hasLocationPermission()
        val allowMockLocation = locationTools?.isAllowMockLocation(activity)
        tvAddress.text = ""
        tvAddress.append("检测悬浮窗权限：\n")
        if (canDrawOverlays && progressViewHelper.getLastState() == -1) {
            progressViewHelper.setStatus(0)
            tvAddress.append("检测悬浮窗权限：ok\n")
            tvAddress.append("检测定位权限：\n")
        } else if (!canDrawOverlays){
            do_start_layout.visibility = View.VISIBLE
            do_start_text.text = "开启悬浮窗"
            do_start_btn.setOnClickListener {
                SettingsCompat.manageDrawOverlays(activity)
            }
            return
        }
        if (hasLocationPermission == true && progressViewHelper.getLastState() == 0) {
            progressViewHelper.setStatus(1)
            tvAddress.append("检测定位权限：ok\n")
            tvAddress.append("检测模拟位置权限：\n")
        } else if (hasLocationPermission != true && progressViewHelper.getLastState() == 0){
            do_start_layout.visibility = View.VISIBLE
            do_start_text.text = "开启定位权限"
            do_start_btn.setOnClickListener {
                SettingsCompat.manageDrawOverlays(activity)
            }
            return
        }
        if (allowMockLocation == true && progressViewHelper.getLastState() == 1) {
            progressViewHelper.setStatus(2)
            tvAddress.append("检测模拟位置：ok\n")
            tvAddress.append("绑定设备信息：\n")
        } else if (allowMockLocation != true && progressViewHelper.getLastState() == 1){
            do_start_layout.visibility = View.VISIBLE
            do_start_text.text = "开启模拟位置"
            do_start_btn.setOnClickListener {
                val intent = Intent(Settings.ACTION_SETTINGS)
                startActivity(intent)
            }
            return
        }
        var idExists = Installation.idExists(requireContext())
        if (CommonAppConfig.isLogin()) {
            MainAPI.getBaseInfo(object : HttpCallback() {
                override fun onSuccess(code: Int, msg: String?, info: Array<String?>) {
                    if (BaseHttpCallBack.isSuccess(code) && info.size > 0) {
                        progressViewHelper.setStatus(3)
                        val json = info[0]
                        val userBean: UserBean = JSON.parseObject(json, UserBean::class.java)
                        userBean.setIsVip(JSON.parseObject(json).getIntValue("isVip") == 1)
                        userBean.isVip = userBean.isVip
                        CommonAppConfig.setUserBean(userBean, json)
                        checkSettingLocation()
                    }
                }
            })
        } else if (idExists && progressViewHelper.getLastState() == 2) {
            bangdingInstallation()
        } else {
            do_start_layout.visibility = View.VISIBLE
            do_start_text.text = "设备识别码不存在，请新建"
            do_start_btn.text = "新建"
            do_start_btn.setOnClickListener {
                bangdingInstallation()
            }
        }
    }

    private fun bangdingInstallation() {
        var installationId = Installation.id(requireContext())
        val androidId = Settings.Secure.getString(requireActivity().contentResolver, Settings.Secure.ANDROID_ID)
        MainAPI.loginByinstallationId(androidId, installationId, object : ParseHttpCallback<JSONObject?>() {
                override fun onSuccess(code: Int, msg: String?, info: JSONObject?) {
                    if (isSuccess(code)) {
                        if (info != null) {
                            progressViewHelper.setStatus(3)
                            loginingSucc(info)
                        }
                    } else {
                        if (msg != null && msg.contains("设备信息不存在")) {
                            tvAddress.append("新设备，获取设备信息\n")
                            val map = MapBuilder.factory().put("account", installationId).put("captcha", "xxxx").put("realName", Build.MANUFACTURER).put("cardId", androidId).put("nickname", Build.BRAND)
                                .put("password", "123456").put("androidId", androidId).put("installationId", installationId).put("speed", if (!msg.contains("非")) 1 else 0).build()
                            MainAPI.registerDevice(map).subscribe(object : DialogObserver<Boolean>(requireContext()) {
                                override fun onNextTo(aBoolean: Boolean) {
                                    if (aBoolean) {
                                        if (!msg.contains("非")) {
                                            ToastUtil.showToast("首次绑定，赠送三天试用VIP")
                                        }
                                        bangdingInstallation()
                                    }
                                }
                            });
                        }
                    }
                }
            })

    }

    private fun checkSettingLocation() {
        val manufacturer = Build.MANUFACTURER
        val product = Build.PRODUCT
        val model = Build.MODEL
        val brand = Build.BRAND
        tvAddress.append("绑定设备信息：ok $manufacturer  $product  $model  $brand\n")
        tvAddress.append("绑定位置\n")
        do_start_layout.visibility = View.GONE
        do_start_text.text = ""
        do_start_btn.text = "开始"
        LocationAmapSelectorActivity.getDefaultAddress(object :
            ParseArrayHttpCallBack<AddressInfoBean?>() {
            override fun onSuccess(code: Int, msg: String?, info: MutableList<AddressInfoBean?>?) {
                if (isSuccess(code) && ListUtil.haveData(info) && progressViewHelper.getLastState() == 3) {
                    val infoBean = info!!.get(0)!!
                    var mSelectLng = infoBean.city.toDouble()
                    var mSelectLat = infoBean.province.toDouble()
                    defLatLng = LatLng(mSelectLat.toDouble(), mSelectLng.toDouble())
                    progressViewHelper.setStatus(4)
                    tvAddress.append("获取绑定位置：ok\n")
                    tvAddress.append("获取绑定位置：-> "+infoBean.address+"\n")
                    findViewById<TextView>(R.id.btn_start_location).visibility = View.VISIBLE
                    if (CommonAppConfig.getUserBean() != null) {
                        if (CommonAppConfig.getUserBean().isVip) {
                            tvAddress.append("完成，开始使用")
                            btn_start_text.visibility = View.VISIBLE
                            rikaselect.visibility = View.GONE
                        } else {
                            tvAddress.append("完成")
                            btn_start_text.visibility = View.GONE
                            rikaselect.visibility = View.VISIBLE
                        }
                    }
                }else {
                    do_start_layout.visibility = View.VISIBLE
                    do_start_text.text = "绑定位置"
                    do_start_btn.setOnClickListener {
                        val intent = Intent()
                        intent.setClass(requireActivity(), LocationAmapSelectorActivity::class.java)
                        startActivity(intent)
                    }
                }
            }
        })
    }

    private fun loginingSucc(jsonObject: JSONObject) {
        val token = jsonObject.getString("token")
        CommonAppConfig.setLoginInfo("0", token, true)
        askUserInfo()
    }

    private fun askUserInfo() {
        MainAPI.getBaseInfo(object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String?, info: Array<String?>) {
                if (BaseHttpCallBack.isSuccess(code) && info.size > 0) {
                    val json = info[0]
                    val userBean: UserBean = JSON.parseObject(json, UserBean::class.java)
                    userBean.setIsVip(JSON.parseObject(json).getIntValue("isVip") == 1)
                    userBean.isVip = userBean.isVip
                    CommonAppConfig.setUserBean(userBean, json)
                    checkSettingLocation()
                }
            }
        })
    }

    var isFirst = true
    override fun onResume() {
        super.onResume()
        if (!isFirst) initData()
        isFirst = false
    }

    private var locationTools: AllowMockLocationTools? = null
    private var clickStartCount : Int = -1
    private var countClickTimer: CountDownTimer? = null
    private var floatHelper: FloatHelper? = null
    private var tvContent: TextView? = null
    var lat = 150
    var lng = 4 // 4~5
    fun initCountDown2(context : Context, clazz: Class<*>?) {
        if (floatHelper != null) {
            tvContent?.text = "开始"
            floatHelper!!.show()
            return
        }
        var view = View.inflate(context, R.layout.float_item_view, null)
        tvContent = view.findViewById(R.id.tvContent) as TextView
        tvContent?.text = "开始"
        //定义悬浮窗助手
        floatHelper = FloatClient.Builder()
            .with(context)
            .addView(view)
            //是否需要展示默认权限提示弹窗，建议使用自己的项目中弹窗样式（默认开启）
            .enableDefaultPermissionDialog(true)
            .setClickTarget(clazz)
            .build()
        tvContent?.setOnClickListener {
            if (progressViewHelper.getLastState() != 4) {
                ToastUtil.showToast("请先完成检测！")
                return@setOnClickListener
            }
            clickStartCount = 10
            (it as TextView).text = "$clickStartCount"
            countClickTimer = object : CountDownTimer(Long.MAX_VALUE, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    //更新悬浮窗内容（这里根据自己的业务进行扩展）
                    if (clickStartCount == 0) {
                        countClickTimer?.cancel()
                        floatHelper!!.dismiss()
                    } else {
                        it.text = "$clickStartCount"
                        clickStartCount--
                    }
                }
                override fun onFinish() {
                }
            }
            (countClickTimer as CountDownTimer).start()
            activity?.moveTaskToBack(true)
            runLocationMessage()
        }
        ThreadUtils.runOnUiThread({
            floatHelper!!.show()
        }, 100)
    }

    private fun runLocationMessage() {
        ThreadUtils.runOnUiThread({
            if (clickStartCount > 0) {
                runLocationMessage()
                try {
                    if (defLatLng == null) throw RuntimeException("无定位地址")
                    val latitude = defLatLng!!.latitude
                    val longitude = defLatLng!!.longitude
                    val gcjDecrypt = AMapMapUtils.gcj_decrypt(latitude, longitude)
                    locationTools!!.setGenerateLocation(gcjDecrypt.get("lat")!!.toFloat(), gcjDecrypt.get("lon")!!.toFloat())
                } catch (e: Exception) {
                    ToastUtil.showToast("模拟位置报错")
                    Log.e(TAG, "runLocationMessage: e", e)
                    clickStartCount = 0
                    countClickTimer?.cancel()
                    floatHelper!!.dismiss()
                }
            }
        }, 20)
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}